using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;

public class SkillManager : MonoBehaviour
{
    public static SkillManager Instance { get; private set; }
    public RectTransform linePrefab;
    public RectTransform startPoint;
    public Transform lightingBox;
    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public IEnumerator OnRefreshSkills()
    {
        // List<Goods> allGoods = new List<Goods>();
        // List<Container> containerList = Data.levelsTransform.GetComponent<Levels>().containers;
        // for (int i = 0; i < containerList.Count; i++)
        // {
        //     Container container = containerList[i];
        //     Goods[] goodsList = container.transform.GetComponentsInChildren<Goods>();
        //     if (goodsList.Length > 0)
        //     {
        //         foreach (var component in goodsList)
        //         {
        //             component.OnRemoveMask();
        //             allGoods.Add(component);
        //             Debug.Log("找到符合类型的组件: " + component.gameObject.name);
        //         }
        //     }
        //     else
        //     {
        //         Debug.Log("没有找到符合类型的组件");
        //     }
        // }

        // Debug.Log("allGoods" + allGoods.Count);
        // //执行动画
        // for (int i = 0; i < allGoods.Count; i++)
        // {
        //     Goods goods = allGoods[i];
        //     goods.transform.parent = Data.levelsTransform;
        //     goods.transform.DOMoveY(goods.transform.position.y - 50, 0.3f);
        // }
        // await FadeManager.Instance.WaitSeconds(0.5f);
        // for (int i = 0; i < allGoods.Count; i++)
        // {
        //     Goods goods = allGoods[i];
        //     //所有的goods移动到父节点的0,0位置
        //     goods.transform.DOMove(Data.levelsTransform.transform.position, 0.5f)
        //         .OnComplete(() =>
        //         {
        //             goods.OnFadeOut();
        //         });
        // }
        // GoodsManager.Instance.ClearAllGoods();

        List<Goods> goodsList = GoodsManager.Instance.GetAllGoods();
        List<int> goodsIdList = new List<int>();

        for (int i = goodsList.Count - 1; i >= 0; i--)
        {
            Goods goods = goodsList[i];
            goodsIdList.Add(goods.goodsId);
            goods.gameObject.SetActive(false);
            GameObject cloneGoods = Instantiate(goods.gameObject);
            cloneGoods.transform.SetParent(Data.levelsTransform);
            cloneGoods.transform.position = goods.transform.position;
            cloneGoods.SetActive(true);
            cloneGoods.GetComponent<Goods>().OnRemoveMask();

            // 创建一个序列
            Sequence sequence = DOTween.Sequence();
            // 按顺序添加两个动画
            sequence.Append(cloneGoods.transform.DOScale(1f, 0.2f))
                    .AppendInterval(0.1f)
                    .Append(cloneGoods.transform.DOMoveY(cloneGoods.transform.position.y - 80, 0.2f))
                    .AppendInterval(0.1f)
                    .Append(cloneGoods.transform.DOMove(Data.levelsTransform.transform.position, 0.5f))
                    .OnComplete(() =>
                        {
                            cloneGoods.GetComponent<Goods>().OnFadeOut();
                        });
        }

        yield return new WaitForSeconds(1.5f);
        //打乱goodsIdList
        List<int> shuffleList = Tools.ShuffleList(goodsIdList);
        Data.levelsTransform.GetComponent<Levels>().OnGenerateNewContainerData(shuffleList);
    }

    public void OnChangeSkills()
    {
        List<Goods> frontGoodsList = new List<Goods>();
        List<Container> containerList = Data.levelsTransform.GetComponent<Levels>().containers;
        for (int i = 0; i < containerList.Count; i++)
        {
            Container container = containerList[i];
            Goods[] goodsList = container.frontObject.GetComponentsInChildren<Goods>();
            if (goodsList.Length > 0)
            {
                foreach (var component in goodsList)
                {
                    frontGoodsList.Add(component);
                    Debug.Log("找到符合类型的组件: " + component.gameObject.name);
                }
            }
            else
            {
                Debug.Log("没有找到符合类型的组件");
            }
        }

        Debug.Log("frontGoodsList" + frontGoodsList.Count);

        List<Goods> randomGoodsList = GetRandomGoods(frontGoodsList);
        Debug.Log("randomGoodsList" + randomGoodsList.Count);
        for (int i = 0; i < randomGoodsList.Count; i++)
        {
            Goods goods = randomGoodsList[i];

            Vector2 screenPoint = Camera.main.WorldToScreenPoint(goods.transform.position);
            RectTransformUtility.ScreenPointToLocalPointInRectangle(lightingBox as RectTransform, screenPoint, Camera.main, out Vector2 localPoint);

            Vector2 screenPoint1 = Camera.main.WorldToScreenPoint(startPoint.position);
            RectTransformUtility.ScreenPointToLocalPointInRectangle(lightingBox as RectTransform, screenPoint1, Camera.main, out Vector2 localPoint1);

            DrawLine(localPoint1, localPoint);
        }

        int randomType = Random.Range(0, Constants.GOODS_COUNT);

        for (int i = 0; i < randomGoodsList.Count; i++)
        {
            Goods goods = randomGoodsList[i];
            goods.shadow.gameObject.SetActive(false);
            goods.icon.transform.DOShakePosition(0.5f, new Vector3(10, 10, 0), 10, 90, false, true) // 抖动效果，持续时间0.5秒
               .OnKill(() => goods.ChangeGoods(randomType));
        }

        StartCoroutine(WaitSeconds(1f));
    }

    public IEnumerator WaitSeconds(float duration)
    {
        yield return new WaitForSeconds(duration);

        foreach (Transform child in lightingBox)
        {
            Destroy(child.gameObject);
        }
    }

    // 获取随机9个元素的函数
    public List<Goods> GetRandomGoods(List<Goods> list)
    {
        // 如果列表中的元素少于9个，直接返回整个列表
        if (list.Count <= 9)
        {
            return list;
        }

        List<Goods> randomGoods = new List<Goods>();

        // 创建一个复制列表来避免改变原始列表
        List<Goods> tempList = new List<Goods>(list);

        // 随机选择9个元素
        for (int i = 0; i < 9; i++)
        {
            // 生成一个随机索引
            int randomIndex = Random.Range(0, tempList.Count);

            // 将随机选中的元素加入返回列表
            randomGoods.Add(tempList[randomIndex]);

            // 从复制列表中移除已经选择的元素，避免重复选择
            tempList.RemoveAt(randomIndex);
        }

        return randomGoods;
    }

    public async void OnChangeContainerStyleSkills()
    {
        int styleId = PlayerPrefs.GetInt("ContainerStyle", 0);
        if (styleId >= 2)
        {
            styleId = -1;
        }
        styleId++;
        PlayerPrefs.SetInt("ContainerStyle", styleId);
        PlayerPrefs.Save();
        Data.StyleId = styleId;

        List<Transform> allContainer = new List<Transform>();
        for (int i = 0; i < Data.levelsTransform.childCount; i++)
        {
            Transform child = Data.levelsTransform.GetChild(i);

            allContainer.Add(child.Find("Container"));
        }
        await FadeManager.Instance.FadeIn();
        for (int i = 0; i < allContainer.Count; i++)
        {
            Transform container = allContainer[i];
            container.GetComponent<Container>().ChangeContainerStyle();
        }
        await FadeManager.Instance.FadeOut();
    }

    public void DrawLine(Vector2 startPos, Vector2 endPos)
    {
        // 创建线条
        RectTransform line = Instantiate(linePrefab, lightingBox);

        // 计算线段的长度和角度
        float distance = Vector2.Distance(startPos, endPos);
        float angle = Mathf.Atan2(endPos.y - startPos.y, endPos.x - startPos.x) * Mathf.Rad2Deg;

        // 设置线条的尺寸
        line.sizeDelta = new Vector2(distance, line.sizeDelta.y);
        RectTransform anim = line.Find("Anim") as RectTransform;

        (anim.Find("1") as RectTransform).sizeDelta = new Vector2(367, distance + 250);
        (anim.Find("2") as RectTransform).sizeDelta = new Vector2(367, distance + 250);
        (anim.Find("3") as RectTransform).sizeDelta = new Vector2(367, distance + 250);
        (anim.Find("4") as RectTransform).sizeDelta = new Vector2(367, distance + 250);

        // 设置线条的旋转角度
        line.rotation = Quaternion.Euler(0, 0, angle);

        // 设置线条的位置，使其从startPos到endPos
        (line.transform as RectTransform).anchoredPosition = startPos + (endPos - startPos) / 2;
    }
}
